package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// AuthMiddleware 返回一个中间件函数，用于验证请求的授权令牌
// 如果令牌有效，请求将继续处理；如果令牌无效，将返回401 Unauthorized错误
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token != "my-secret-token" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}
		c.Next()
	}
}

func main() {
	r := gin.Default()

	// 不需要认证的公开路由
	public := r.Group("/public")
	{
		public.GET("/ping", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"message": "pong"})
		})
	}

	// 需要认证的受保护路由
	// 使用AuthMiddleware中间件来验证请求的授权令牌
	protected := r.Group("/protected", AuthMiddleware())
	{
		protected.GET("/dashboard", func(c *gin.Context) {
			c.JSON(http.StatusOK, gin.H{"message": "Welcome to the dashboard"})
		})
	}

	r.Run(":8080")
}
